<template>
  <nav v-if="links.length > 3" class="flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 sm:px-6">
    <div class="flex flex-1 justify-between sm:hidden">
      <Link
        v-if="links[0].url"
        :href="links[0].url"
        class="relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
        v-html="links[0].label"
      />
      <Link
        v-if="links[links.length - 1].url"
        :href="links[links.length - 1].url"
        class="relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
        v-html="links[links.length - 1].label"
      />
    </div>
    <div class="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
      <div>
        <p class="text-sm text-gray-700">
          显示第
          <span class="font-medium">{{ from }}</span>
          到
          <span class="font-medium">{{ to }}</span>
          条，共
          <span class="font-medium">{{ total }}</span>
          条记录
        </p>
      </div>
      <div>
        <nav class="isolate inline-flex -space-x-px rounded-md shadow-sm" aria-label="Pagination">
          <Link
            v-for="(link, index) in links"
            :key="index"
            :href="link.url"
            v-html="link.label"
            :class="[
              'relative inline-flex items-center px-4 py-2 text-sm font-semibold ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0',
              index === 0 ? 'rounded-l-md' : '',
              index === links.length - 1 ? 'rounded-r-md' : '',
              link.active
                ? 'z-10 bg-orange-600 text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-600'
                : 'text-gray-900'
            ]"
          />
        </nav>
      </div>
    </div>
  </nav>
</template>

<script setup>
import { computed } from 'vue'
import { Link } from '@inertiajs/vue3'

const props = defineProps({
  links: {
    type: Array,
    required: true
  }
})

const from = computed(() => {
  const firstLink = props.links.find(link => link.label.includes('上一页') || link.label.includes('Previous'))
  if (firstLink && firstLink.url) {
    const url = new URL(firstLink.url, window.location.origin)
    const page = parseInt(url.searchParams.get('page')) || 1
    return (page - 1) * 10 + 1
  }
  return 1
})

const to = computed(() => {
  const lastLink = props.links.find(link => link.label.includes('下一页') || link.label.includes('Next'))
  if (lastLink && lastLink.url) {
    const url = new URL(lastLink.url, window.location.origin)
    const page = parseInt(url.searchParams.get('page')) || 1
    return page * 10
  }
  return props.links.length > 0 ? 10 : 0
})

const total = computed(() => {
  // 这里需要从后端获取总数，暂时返回估算值
  return to.value
})
</script>
